package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueFailAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueFailResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.ClueIntentionGradeDataRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.UpdateClueEmpRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.EmployeeResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.qwSystem.QwSystmeClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.qwSystem.request.WxCpUserListRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.qwSystem.response.WxAgenDetailResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.TenantClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.response.DictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.todo.IMsgTodoClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.todo.request.CustomButtonRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.todo.request.TodoAccessRequest;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.Clue;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueCustomerCollect;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueFail;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueTodoRel;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.DealerCustomer;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueFailManager;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueTodoRelManager;
import com.tencent.iov.cowin.befsale.clue.repository.cus.DealerCustomerManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueCustomerCollectService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueFailService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueService;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.*;
import com.software.boot.weixin.cp.bean.WxCpAgent;
import com.software.boot.weixin.cp.bean.WxCpTagGetResult;
import com.software.boot.weixin.cp.bean.WxCpUser;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import com.software.common.enums.StatusEnum;
import com.software.common.utils.BasePropertyInjection;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Describe: 线索战败审批信息表_Service实现层
 * @author: whp
 * @created: 2021-12-21 16:16:09
 * @version: 1.0
 */
@Service
@Slf4j
public class ClueFailServiceImpl implements ClueFailService {

    @Autowired
    private ClueFailManager clueFailManager;
    @Autowired
    //@Lazy
    private ClueService clueService;
    @Autowired
    private ClueCustomerCollectService clueCustomerCollectService;
    @Autowired
    private OemCustomerFollowRecordService oemCustomerFollowRecordService;
    @Autowired
    private DealerCustomerFollowRecordService dealerCustomerFollowRecordService;
    @Autowired
    private DealerCustomerManager dealerCustomerManager;
    @Autowired
    private ClueTodoRelManager clueTodoRelManager;
    @Autowired
    private IMsgTodoClient msgTodoClient;
    @Autowired
    private QwSystmeClient qwSystmeClient;
    @Autowired
    private MdQueryClient mdQueryClient;
    @Autowired
    private TenantClient tenantClient;

    //代办配置时间 审核
    @Value("${clue-todo.time.examine}")
    private Integer examineTime;
    @Value("${clue-todo.template.msgTodoExamineClue.id}")
    private Long examineTodoId;

    private static final Integer SUCCESS_CODE = 0;

    @Override
    public ClueFailResponse getDetailById(Long id) {
        //验证请求参数
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        //处理业务
        ClueFail clueFail = clueFailManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(clueFail)) {
            return BeanUtil.copy(clueFail, ClueFailResponse.class);
        }
        //返回结果
        return null;
    }

    /**
     * 单条数据插入ClueFail
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public Long insert(ClueFail request) {
        Long clueId = request.getClueId();
        //参数验证--申请线索id验证
        if (clueId == null) {
            throw new BusinessException(ClueErrorEnum.CLUE_FAIL_ADD_REQUEST_ERROR);
        }
        //参数验证--申请人empId验证
        String followEmpId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        if (StringUtils.isEmpty(followEmpId)) {
            throw new BusinessException(ClueErrorEnum.CLUE_FAIL_ADD_RES_EMPID_NULL_ERROR);
        }
        //参数验证--战败主因
        if (StringUtils.isEmpty(request.getFailReasonCodes())) {
            throw new BusinessException(ClueErrorEnum.CLUE_FAIL_ADD_RES_REASON_NULL_ERROR);
        }
        //参数验证--战败备注
       /* if(StringUtils.isEmpty(request.getFailRemark())){
            throw new BusinessException(ClueErrorEnum.CLUE_FAIL_ADD_RES_REMARK_NULL_ERROR);
        }*/

        //参数验证--客户id验证
        if (request.getCusId() == null) {
            throw new BusinessException(ClueErrorEnum.CLUE_FAIL_ADD_RES_CUSID_NULL_ERROR);
        }

        //参数验证--线索是否存在验证
        Clue clue = clueService.getDetailById(clueId);
        if (clue == null) {
            throw new BusinessException(ClueErrorEnum.CLUE_FAIL_ADD_RES_CLUE_NULL_ERROR);
        }
        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
        //业务处理-战败申请基本信息赋值
        request.setClueStatus(clue.getStatus());
        request.setFollowEmpId(Long.valueOf(followEmpId));
        request.setStatus(FailStatusEnum.APPROVAL_PENDING.getCode());
        clueFailManager.insert(request);
        Long failId = request.getId();
        //战败申请成功后--修改线索信息
        Clue clueUpdate = new Clue();
        clueUpdate.setId(clueId);
        clueUpdate.setStatus(ClueStatsEnum.FAIL_APPROVE.getCode());
        clueUpdate.setIsActive(IsActiveEnum.ACTIVE_YES.getCode());
        clueUpdate.setUpdatedName(request.getUpdatedName());
        clueUpdate.setUpdatedBy(request.getUpdatedBy());
        clueUpdate.setUpdatedTime(request.getUpdatedTime());
        clueService.update(clueUpdate);
        //战败申请成功后--修改搜索宽表信息
        ClueCustomerCollect queryClueCollect = new ClueCustomerCollect();
        queryClueCollect.setClueId(clueId);
        queryClueCollect.setDeleted(DeleteEnum.INIT.getFlag());
        ClueCustomerCollect exist = clueCustomerCollectService.getOneByParam(queryClueCollect);

        ClueCustomerCollect collectUpdate = new ClueCustomerCollect();
        collectUpdate.setClueId(clueId);
        collectUpdate.setClueStatus(ClueStatsEnum.FAIL_APPROVE.getCode());
        collectUpdate.setFailEmpId(Long.valueOf(followEmpId));
        collectUpdate.setFailCreatedTime(request.getCreatedTime());
        collectUpdate.setFailReasonCodes(request.getFailReasonCodes());
        collectUpdate.setFailRemark(request.getFailRemark());
        collectUpdate.setFailStatus(FailStatusEnum.APPROVAL_PENDING.getCode());
        collectUpdate.setUpdatedName(request.getUpdatedName());
        collectUpdate.setUpdatedBy(request.getUpdatedBy());
        collectUpdate.setUpdatedTime(request.getUpdatedTime());
        if (exist != null) {
            collectUpdate.setFollowNum(exist.getFollowNum() == null ? 1 : exist.getFollowNum() + 1);
        }
        int count = clueCustomerCollectService.updateByClueId(collectUpdate);
        //战败申请成功后--根据是否是经销商 记录战败申请记录
        AddCustomerFollowRecordRequest recordRequest = new AddCustomerFollowRecordRequest();
        BasePropertyInjection.savePropertyInjection(recordRequest);
        recordRequest.setClueId(clueId);
        recordRequest.setStatus(FollowRecordStatusEnum.FOLLOW_UP.getCode());
        recordRequest.setSecondStatus(FollowRecordSecondStatusEnum.FOLLOW_FAIL_APPLY.getCode());
        recordRequest.setRemark(request.getFailRemark());
        recordRequest.setOperateTime(request.getCreatedTime());
        recordRequest.setFailId(failId);
        recordRequest.setCusId(request.getCusId());
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            //如果进销商为空，则记录入库总部客户记录表
            oemCustomerFollowRecordService.insert(recordRequest);
        } else {
            //如果经销商不为空，则记录入库经销商客户记录表
            recordRequest.setDealerId(dealerId);
            dealerCustomerFollowRecordService.insert(recordRequest);
        }
        //对接待办
        try {
            makeExamineTodoTask(request, dealerId);
        } catch (Exception e) {
            log.info("[insert][makeExamineTodoTask] 同步战败状态到代班失败, request={}, dealerId={}, exception={}", recordRequest, dealerId, e);
        }

        /** 3 封装返回值 */
        return failId;
    }

    private void makeExamineTodoTask(ClueFail request, String dealerId) {
        log.info("线索审核对接代办");
        QueryDictionariesRequest queryDictionariesRequest = new QueryDictionariesRequest();
        queryDictionariesRequest.setCode(request.getFailReasonCodes());
        List<DictionariesResponse> dictionariesResponses = tenantClient.getDictionariesListByParam(queryDictionariesRequest).getData();
        String reason = "";
        if (CollectionUtils.isNotEmpty(dictionariesResponses)) {
            reason = dictionariesResponses.get(0).getName();
        }


        String empName = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_NAME.getCode());
        DealerCustomer customer = dealerCustomerManager.getDetailById(request.getCusId());

        //代办模板对应的map
        Map<String, Object> todoMap = new HashMap<>();
        todoMap.put("date", DateUtil.toDateString(new Date(), "yyyy-MM-dd HH:mm"));
        todoMap.put("empName", empName);
        todoMap.put("reason", reason);
        todoMap.put("remark", request.getFailRemark());
        todoMap.put("name", customer.getName());
        todoMap.put("phone", customer.getPhone());

        //查询经销商&总部管理员
        List<Long> empIds = new ArrayList<>();

        log.info("调用qwSystem获取应用详情，入参：{}", JsonUtils.object2JSON(AgentTypeEnum.CLUB_MANAGER));
        WxAgenDetailResponse detailInfo = qwSystmeClient.agentDetail(AgentTypeEnum.CLUB_MANAGER).getData();
        log.info("调用qwSystem获取应用详情，出参：{}", detailInfo);
        if (detailInfo != null && detailInfo.getErrCode().equals(SUCCESS_CODE)) {
            //获取应用下用户，部门和可见标签
            List<String> userIds = new ArrayList<>();
            if(Objects.nonNull(detailInfo.getAllowUserInfos())){
                List<WxAgenDetailResponse.User> users = detailInfo.getAllowUserInfos().getUsers();
                List<String> collect = users.stream().map(item -> item.getUserId()).collect(Collectors.toList());
                userIds.addAll(collect);
            }
            if(detailInfo.getAllowParties() != null && CollectionUtils.isNotEmpty(detailInfo.getAllowParties().getPartyIds())){
                List<Integer> partyIds = detailInfo.getAllowParties().getPartyIds();
                WxCpUserListRequest userListRequest = new WxCpUserListRequest();
                partyIds.forEach(partyId->{
                    userListRequest.setDepartId(partyId.longValue());
                    userListRequest.setFetchChild(true);
                    log.info("调用qwSystem获取部门成员，入参：{}", JSON.toJSONString(userListRequest));
                    List<WxCpUser> data = qwSystmeClient.userList(userListRequest).getData();
                    log.info("调用qwSystem获取部门成员，出参：{}", JsonUtils.object2JSON(data));
                    List<String> collect = data.stream().map(item -> item.getUserId()).collect(Collectors.toList());
                    userIds.addAll(collect);
                });
            }

            if(detailInfo.getAllowTags() != null && CollectionUtils.isNotEmpty(detailInfo.getAllowTags().getTagIds())){
                List<Integer> tagIds = detailInfo.getAllowTags().getTagIds();
                tagIds.forEach(tagId->{
                    log.info("调用qwSystem获取标签成员，入参：{}", tagIds);
                    WxCpTagGetResult tagGetResult = qwSystmeClient.getTag(tagId).getData();
                    log.info("调用qwSystem获取标签成员，出参：{}", JsonUtils.object2JSON(tagGetResult));
                    List<String> collect = tagGetResult.getUserlist().stream().map(item -> item.getUserId()).collect(Collectors.toList());
                    userIds.addAll(collect);
                });
            }
            if(CollectionUtils.isEmpty(userIds)){
                log.info("发送待办，执行人为空");
                return;
            }

            if (CollectionUtils.isNotEmpty(userIds)) {
                log.info("调用mdQuery获取顾问信息，入参：{}", JsonUtils.object2JSON(userIds));
                List<EmployeeResponse> empList = mdQueryClient.getUserNameByUserId(userIds).getData();
                log.info("调用mdQuery获取顾问信息，出参：{}", empList);
                if (CollectionUtils.isNotEmpty(empList)) {
                    empIds.addAll(empList.stream().filter(e -> e.getDealerId() == null || e.getDealerId().equals(dealerId))
                            .map(EmployeeResponse::getId).collect(Collectors.toList()));
                }
            }
        }
        //代办按钮
        List<CustomButtonRequest> buttonRequestList = new ArrayList<>();
        CustomButtonRequest customButtonRequest = new CustomButtonRequest();
        customButtonRequest.setName(MsgTodoEnum.BTN_EXAMINE_CLUE.getName());
        customButtonRequest.setEvent(MsgTodoEnum.BTN_EXAMINE_CLUE.getCode());
        customButtonRequest.setUrl("/clue/administrators/?active=3");
        buttonRequestList.add(customButtonRequest);

        String title = "待审核线索-" + customer.getName();
        String content = "战败申请:" + DateUtil.toDateString(new Date(), "yyyy-MM-dd HH:mm") +
                "|" + empName + " \n战败原因:" + reason + "|" + request.getFailRemark() + " \n客户:" + customer.getName() + "|" + customer.getPhone();
        //代办截止时间
        Date dueDate = DateUtil.addHours(new Date(), examineTime);
        makeTodoTask(buttonRequestList, examineTodoId, title, content, MsgTodoEnum.EXAMINE_CLUE.getCode(), empIds, todoMap, dueDate, request.getClueId(), customer.getPhone(),null,null,null);
    }

    /**
     * 创建代办任务
     *
     * @param buttonRequestList 按钮list
     * @param templateId        模板id
     * @param title             代办title
     * @param content           代办内容
     * @param businessType      业务类型
     * @param empIds            代办所有人
     * @param paramData         模板对应map
     * @param dueTime           截止时间
     * @param businessId        代办对应业务id
     */
    @Override
    public void makeTodoTask(List<CustomButtonRequest> buttonRequestList, Long templateId, String title, String content,
                             String businessType, List<Long> empIds, Map<String, Object> paramData, Date dueTime,
                             Long businessId, String phone,String tenantId,String corpId,
                             String externalUserid) {
        if (empIds != null) {
            empIds = empIds.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        }
        if (CollectionUtils.isNotEmpty(empIds)) {
            TodoAccessRequest todoAccessRequest = new TodoAccessRequest();
            todoAccessRequest.setCustomButtonList(buttonRequestList);
            todoAccessRequest.setTemplateId(templateId);
            todoAccessRequest.setTitle(title);
            todoAccessRequest.setContent(content);
            todoAccessRequest.setBusinessType(businessType);

            todoAccessRequest.setEmpIds(empIds);
            todoAccessRequest.setParamData(paramData);
            todoAccessRequest.setDueTime(dueTime);
            todoAccessRequest.setCustomerPhone(phone);
            todoAccessRequest.setExternalUserId(externalUserid);

            String corp = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode());
            String tenant = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode());
            if(org.apache.commons.lang3.StringUtils.isBlank(corp)){
                corp = corpId;
            }
            if(org.apache.commons.lang3.StringUtils.isBlank(tenant)){
                tenant = tenantId;
            }
            log.info("调用msgTodo创建代办，入参:{}", JsonUtils.object2JSON(todoAccessRequest));
            Long todoId = msgTodoClient.createTodoItem(corp, tenant, todoAccessRequest).getData();

            //记录线索代办关联表
            clueTodoRecord(businessType, empIds, businessId, todoId);
        }


    }

    private void clueTodoRecord(String businessType, List<Long> empIds, Long businessId, Long todoId) {
        List<ClueTodoRel> clueTodoRels = new ArrayList<>();
        for (Long empId : empIds) {
            ClueTodoRel clueTodoRel = new ClueTodoRel();
            clueTodoRel.setTodoId(todoId);
            clueTodoRel.setBusinessId(businessId);
            clueTodoRel.setBusinessType(businessType);
            clueTodoRel.setEmpId(empId);
            clueTodoRel.setStatus(StatusEnum.INIT.getFlag());
            BasePropertyInjection.savePropertyInjection(clueTodoRel);
            clueTodoRels.add(clueTodoRel);
        }
        if (CollectionUtils.isNotEmpty(clueTodoRels)) {
            clueTodoRelManager.insertBatch(clueTodoRels);
        }
    }

    /**
     * 批量插入ClueFail
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<ClueFail> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueFailManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }


    /**
     * 单条ClueFail更新
     *
     * @param request
     * @return 更新的条数
     */
    @Override
    public int update(ClueFail request) {

        /** 1 验证请求参数 */
        /** 2 处理业务 */
        /** 3 返回对象 */
        return clueFailManager.update(request);
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(ClueFail request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueFail clueFail = new ClueFail();
        clueFail.setId(id);
//		clueFail.setDelete(DeleteEnum.DETELED.getCode());
        int count = clueFailManager.update(clueFail);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<ClueFail> getListByParam(ClueFail request) {
        /** 1 验证请求参数 */
        //可以设置排序

        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        /** 2 处理业务 */
        List<ClueFail> queryList = clueFailManager.getListByParam(request);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, ClueFail.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<ClueFail> getPageByParam(PageRequest<ClueFail> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());

        ClueFail query = request.getParamData();
        query.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        query.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        query.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        Page<ClueFail> queryPageList = clueFailManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<ClueFail> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueFail.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    /**
     * 查看待审批的战败申请数量
     * add by zly
     *
     * @param clueIntentionGradeDataRequest
     * @return
     */
    @Override
    public Integer getApprovelCount(ClueIntentionGradeDataRequest clueIntentionGradeDataRequest) {
        return clueFailManager.getApprovelCount(clueIntentionGradeDataRequest);
    }

    @Override
    public ClueFail getOneByParam(ClueFail request) {
        return clueFailManager.getOneByParam(request);
    }

    @Override
    public ClueFail updateByFailInfo(UpdateClueEmpRequest request) {
        FailStatusEnum failStatusEnum = FailStatusEnum.getByCode(request.getFailStatus());
        if (EmptyUtils.isEmpty(failStatusEnum)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索审批-线索状态枚举不存在");
        }
        ClueFail queryClueFail = ClueFailAssembler.initQueryInfo(request, failStatusEnum);
        queryClueFail.setOrderFields(Lists.newArrayList(new OrderField("id", "DESC")));
        ClueFail clueFail = clueFailManager.getOneByParam(queryClueFail);
        if (EmptyUtils.isEmpty(clueFail)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索审批-线索战败审批信息不存在");
        }

        ClueFail updateClueFail = new ClueFail();
        updateClueFail.setStatus(request.getFailStatus());
        updateClueFail.setDeleted(DeleteEnum.INIT.getFlag());
        updateClueFail.setApproveRemark(request.getApproveRemark());
        updateClueFail.setId(clueFail.getId());
        int result = clueFailManager.update(updateClueFail);
        if (result <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索审批-线索战败审批更新失败");
        }

        return clueFail;
    }
}
